<%#
 Copyright 2013-2025 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      https://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
<%_
const order = 'desc';
const testEntityPrimaryKey = tsPrimaryKeySamples[0];
const testEntityPrimaryKey2 = tsPrimaryKeySamples[1];
_%>
<%_ if (clientTestFrameworkVitest) { _%>
import { MockInstance, afterEach, beforeEach, describe, expect, it, vitest } from 'vitest';
<%_ } _%>
import { provideHttpClient, HttpHeaders, HttpResponse } from '@angular/common/http';
import { provideHttpClientTesting } from '@angular/common/http/testing';
import {
  ComponentFixture, TestBed,
<%_ if (!readOnly) { _%>
  inject,
<%_ } _%>
} from '@angular/core/testing';
import { ActivatedRoute, convertToParamMap } from '@angular/router';

import { FaIconLibrary } from '@fortawesome/angular-fontawesome';
import { faEye, faPencilAlt, faPlus, faSort, faSortDown, faSortUp, faSync, faTimes } from '@fortawesome/free-solid-svg-icons';
<%_ if (enableTranslation) { _%>
import { TranslateModule } from '@ngx-translate/core';
<%_ } _%>
import {
  of,
<%_ if (!readOnly) { _%>
  Subject,
<%_ } _%>
} from 'rxjs';
<%_ if (!readOnly) { _%>
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
<%_ } _%>

<%_ if (!readOnly) { _%>
import { sampleWithRequiredData } from '../<%= entityFileName %>.test-samples';
<%_ } _%>
import { <%= entityAngularName %>Service } from '../service/<%= entityFileName %>.service';

import { <%= entityAngularName %> } from './<%= entityFileName %>';

describe('<%= entityAngularName %> Management Component', () => {
    let comp: <%= entityAngularName %>;
    let fixture: ComponentFixture<<%= entityAngularName %>>;
    let service: <%= entityAngularName %>Service;
    let routerNavigateSpy: <%- clientTestFrameworkJest ? 'jest.SpyInstance<Promise<boolean>>' : 'MockInstance' %>;

    beforeEach(() => {
        TestBed.configureTestingModule({
            <%_ if (enableTranslation) { _%>imports: [TranslateModule.forRoot()],<%_ } _%>
            providers: [
                provideHttpClient(),
                provideHttpClientTesting(),
                {
                    provide: ActivatedRoute,
                    useValue: {
                        data: of({
                            defaultSort: '<%- primaryKey.name %>,asc',
                        }),
                        queryParamMap: of(
                            convertToParamMap({
                                page: '1',
                                size: '1',
                                sort: '<%- primaryKey.name %>,desc',
<%_ if (jpaMetamodelFiltering) { _%>
                                'filter[someId.in]': 'dc4279ea-cfb9-11ec-9d64-0242ac120002',
<%_ } _%>
                            })
                        ),
                        snapshot: {
                            queryParams: {},
                            queryParamMap: convertToParamMap({
                                page: '1',
                                size: '1',
                                sort: '<%- primaryKey.name %>,desc',
<%_ if (jpaMetamodelFiltering) { _%>
                                'filter[someId.in]': 'dc4279ea-cfb9-11ec-9d64-0242ac120002',
<%_ } _%>
                            }),
                        },
                    }
                }
            ]
        });

        fixture = TestBed.createComponent(<%= entityAngularName %>);
        comp = fixture.componentInstance;
        service = TestBed.inject(<%= entityAngularName %>Service);
        routerNavigateSpy = <%= clientTestFramework %>.spyOn(comp.router, 'navigate');

        <%= clientTestFramework %>
          .spyOn(service, 'query')
          .mockReturnValueOnce(
            of(
              new HttpResponse({
                body: [<%- testEntityPrimaryKey %>],
                headers: new HttpHeaders({
                  link: '<http://localhost/api/foo?page=1&size=20>; rel="next"',
                }),
              }),
            ),
          )
          .mockReturnValueOnce(
            of(
              new HttpResponse({
                body: [<%- testEntityPrimaryKey2 %>],
                headers: new HttpHeaders({
                  link: '<http://localhost/api/foo?page=0&size=20>; rel="prev",<http://localhost/api/foo?page=2&size=20>; rel="next"',
                }),
              }),
            ),
          );

    const library = TestBed.inject(FaIconLibrary);
    library.addIcons(faEye, faPencilAlt, faPlus, faSort, faSortDown, faSortUp, faSync, faTimes);
  });

    it('should call load all on init', () => {
        // WHEN
        comp.ngOnInit();

        // THEN
        expect(service.query).toHaveBeenCalled();
        expect(comp.<%= entityInstancePlural %>()[0]).toEqual(expect.objectContaining(<%- testEntityPrimaryKey %>));
    });

    describe('track<%= primaryKey.nameCapitalized %>', () => {
        it('should forward to <%= entityInstance %>Service', () => {
            const entity = <%- tsPrimaryKeySamples[0] %>;
            <%= clientTestFramework %>.spyOn(service, 'get<%= entityAngularName %>Identifier');
            const <%= primaryKey.name %> = comp.track<%= primaryKey.nameCapitalized %>(entity);
            expect(service.get<%= entityAngularName %>Identifier).toHaveBeenCalledWith(entity);
            expect(<%= primaryKey.name %>).toBe(entity.<%= primaryKey.name %>);
        });
    });

    it('should calculate the sort attribute for a non-id attribute', () => {
        // WHEN
        comp.navigateToWithComponentValues({ predicate: 'non-existing-column', order: 'asc' });

        // THEN
        expect(routerNavigateSpy).toHaveBeenLastCalledWith(expect.anything(),
          expect.objectContaining({
            queryParams: expect.objectContaining({
                sort: ['non-existing-column,asc']
              })
          }));
    });
<%_ if (paginationPagination) { _%>

    it('should load a page', () => {
        // WHEN
        comp.navigateToPage(1);

        // THEN
        expect(routerNavigateSpy).toHaveBeenCalled();
    });
<%_ } _%>

    it('should calculate the sort attribute for an id', () => {
        // WHEN
        comp.ngOnInit();

        // THEN
        expect(service.query).toHaveBeenLastCalledWith(expect.objectContaining({ sort: ['<%- primaryKey.fields.map(field => field.fieldName).join(',') %>,<%= order %>'] }));
    });
<%_ if (paginationInfiniteScroll) { _%>

  it('should infinite scroll', () => {
    // GIVEN
    comp.loadNextPage();
    comp.loadNextPage();
    comp.loadNextPage();

    // THEN
    expect(service.query).toHaveBeenCalledTimes(3);
    expect(service.query).toHaveBeenNthCalledWith(2, expect.objectContaining({ page: '1' }));
    expect(service.query).toHaveBeenLastCalledWith(expect.objectContaining({ page: '2' }));
  });
<%_ } _%>
<%_ if (jpaMetamodelFiltering && paginationPagination) { _%>

  it('should calculate the filter attribute', () => {
    // WHEN
    comp.ngOnInit();

    // THEN
    expect(service.query).toHaveBeenLastCalledWith(expect.objectContaining({ 'someId.in': ['dc4279ea-cfb9-11ec-9d64-0242ac120002'] }));
  });
<%_ } _%>
<%_ if (!readOnly) { _%>

  describe('delete', () => {
    let ngbModal: NgbModal;
    let deleteModalMock: any;

    beforeEach(() => {
      deleteModalMock = { componentInstance: {}, closed: new Subject() };
      // NgbModal is not a singleton using TestBed.inject.
      // ngbModal = TestBed.inject(NgbModal);
      ngbModal = (comp as any).modalService;
      <%= clientTestFramework %>.spyOn(ngbModal, 'open').mockReturnValue(deleteModalMock);
    });

    it('on confirm should call load', inject([], () => {
      // GIVEN
      <%= clientTestFramework %>.spyOn(comp, 'load');

      // WHEN
      comp.delete(sampleWithRequiredData);
      deleteModalMock.closed.next('deleted');

      // THEN
      expect(ngbModal.open).toHaveBeenCalled();
      expect(comp.load).toHaveBeenCalled();
    }));

    it('on dismiss should call load', inject([], () => {
      // GIVEN
      <%= clientTestFramework %>.spyOn(comp, 'load');

      // WHEN
      comp.delete(sampleWithRequiredData);
      deleteModalMock.closed.next();

      // THEN
      expect(ngbModal.open).toHaveBeenCalled();
      expect(comp.load).not.toHaveBeenCalled();
    }));
  });
<%_ } _%>
});
